import 'package:bitcoin_mine/common/global.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../controllers/withdraw_controller.dart';
import '../l10n/app_localizations.dart';

class WithdrawPage extends StatelessWidget {
  const WithdrawPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 初始化提现控制器
    Get.put(WithdrawController());
    final l10n = AppLocalizations.of(context);

    return Scaffold(
      backgroundColor: const Color(0xFF0A0E27),
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white),
          onPressed: () => Get.find<WithdrawController>().goBack(),
        ),
        title: Text(
          l10n.withdraw,
          style: TextStyle(
            color: Colors.white,
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: GestureDetector(
        onTap: () {
          // 点击外部关闭弹窗
          Get.find<WithdrawController>().closeMethodSelector();
        },
        child: Stack(
          children: [
            SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              child: Column(
                children: [
                  SizedBox(height: 20.h),

                  // 比特币图标和标题
                  _buildBitcoinHeader(l10n),

                  SizedBox(height: 30.h),

                  // 提现方式选择
                  _buildWithdrawalMethod(),

                  SizedBox(height: 20.h),

                  // 提现规则
                  _buildWithdrawalRules(l10n),

                  SizedBox(height: 20.h),

                  // 提现地址输入
                  _buildWithdrawalAddress(l10n),

                  SizedBox(height: 10.h),

                  // 提现金额输入
                  _buildWithdrawalAmount(l10n),

                  SizedBox(height: 10.h),

                  // 余额信息
                  _buildBalanceInfo(l10n),

                  SizedBox(height: 40.h),

                  // 提现按钮
                  _buildWithdrawButton(l10n),

                  SizedBox(height: 20.h),
                ],
              ),
            ),

            // 提现方式选择弹窗
            _buildMethodSelectorPopup(l10n),
          ],
        ),
      ),
    );
  }

  Widget _buildBitcoinHeader(AppLocalizations l10n) {
    return Column(
      children: [
        // 比特币图标
        Image.asset(
          "assets/images/icon_bit_coin.png",
          width: 80.w,
          height: 80.w,
        ),

        SizedBox(height: 16.h),

        // 标题
        Text(
          l10n.withdrawBitcoin,
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.w400,
          ),
        ),

        // 副标题
        Text(
          l10n.withdrawBitcoinToAccount,
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.w400,
          ),
        ),
      ],
    );
  }

  Widget _buildWithdrawalMethod() {
    return GetBuilder<WithdrawController>(
      builder:
          (controller) => GestureDetector(
            onTap: () => _showMethodSelector(),
            child: Container(
              padding: EdgeInsets.only(left: 16.w),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage("assets/images/bg_section.png"),
                  fit: BoxFit.fill,
                ),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Row(
                      children: [
                        Obx(
                          () => Text(
                            controller.selectedMethod.value,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        SizedBox(width: 3.w),
                        Text(
                          // l10n.clickForGuide,
                          "",
                          style: TextStyle(
                            color: const Color(0xFF05FFFD),
                            fontSize: 14.sp,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Image.asset(
                    "assets/images/icon_selection_arrow.png",
                    width: 50.r,
                    height: 50.r,
                  ),
                ],
              ),
            ),
          ),
    );
  }

  Widget _buildWithdrawalRules(AppLocalizations l10n) {
    return GetBuilder<WithdrawController>(
      builder:
          (controller) => Column(
            children: [
              _buildRuleItem(
                l10n.minimumWithdrawalAmount,
                '${Global.mineInfo.value?.withdraw_rule.min_withdrawal.toStringAsFixed(8)} btc',
              ),
              SizedBox(height: 3.h),
              _buildRuleItem(
                l10n.maximumWithdrawalAmount,
                '${Global.mineInfo.value?.withdraw_rule.max_withdrawal.toStringAsFixed(8)} btc',
              ),
              SizedBox(height: 3.h),
              _buildRuleItem(
                l10n.withdrawalFee,
                '${Global.mineInfo.value?.withdraw_rule.withdrawal_fee.toStringAsFixed(8)} btc',
              ),
            ],
          ),
    );
  }

  Widget _buildRuleItem(String label, String value) {
    return Row(
      children: [
        Icon(Icons.help, color: const Color(0xFF00FFFF), size: 16.sp),
        SizedBox(width: 8.w),
        Expanded(
          child: Text(
            label,
            style: TextStyle(
              color: Colors.white70,
              fontSize: 12.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
        Text(
          value,
          style: TextStyle(
            color: const Color(0xFF00FFFF),
            fontSize: 12.sp,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  Widget _buildWithdrawalAddress(AppLocalizations l10n) {
    return GetBuilder<WithdrawController>(
      builder:
          (controller) => Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                l10n.withdrawalAddress,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(height: 8.h),
              Container(
                height: 50.h,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("assets/images/bg_selection.png"),
                    fit: BoxFit.fill,
                  ),
                ),
                child: Row(
                  children: [
                    SizedBox(width: 16.w),
                    Expanded(
                      child: TextField(
                        onTapOutside:
                            (event) =>
                                FocusManager.instance.primaryFocus?.unfocus(),
                        controller: TextEditingController(
                          text: controller.withdrawalAddress.value,
                        ),
                        onChanged: controller.setWithdrawalAddress,
                        style: TextStyle(color: Colors.white, fontSize: 14.sp),
                        decoration: InputDecoration(
                          hintText: l10n.fillWithdrawalAddress,
                          hintStyle: TextStyle(
                            color: Color(0xFF05FFFD),
                            fontSize: 14.sp,
                          ),
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    SizedBox(width: 8.w),
                    GestureDetector(
                      onTap: controller.copyAddress,
                      child: Container(
                        alignment: Alignment.center,
                        height: 50.h,
                        width: 78.w,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage("assets/images/btn_copy_all.png"),
                            fit: BoxFit.fill,
                          ),
                        ),
                        child: Text(
                          l10n.copy,
                          style: TextStyle(
                            color: const Color(0xFFFFFFFF),
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
    );
  }

  Widget _buildWithdrawalAmount(AppLocalizations l10n) {
    return GetBuilder<WithdrawController>(
      builder:
          (controller) => Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                l10n.withdrawalAmount,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(height: 8.h),
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("assets/images/bg_selection.png"),
                    fit: BoxFit.fill,
                  ),
                ),
                child: Row(
                  children: [
                    SizedBox(width: 16.w),
                    Expanded(
                      child: TextField(
                        controller: TextEditingController(
                          text: controller.withdrawalAmount.value,
                        ),
                        onTapOutside:
                            (event) =>
                                FocusManager.instance.primaryFocus?.unfocus(),
                        onChanged: controller.setWithdrawalAmount,
                        keyboardType: TextInputType.number,
                        style: TextStyle(color: Colors.white, fontSize: 14.sp),
                        decoration: InputDecoration(
                          hintText: l10n.enterWithdrawalAmount,
                          hintStyle: TextStyle(
                            color: Color(0xFF05FFFD),
                            fontSize: 14.sp,
                          ),
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    Text(
                      'btc',
                      style: TextStyle(
                        color: Colors.white70,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(width: 8.w),
                    GestureDetector(
                      onTap: controller.useAllBalance,
                      child: Container(
                        height: 50.h,
                        width: 78.w,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage("assets/images/btn_copy_all.png"),
                            fit: BoxFit.fill,
                          ),
                        ),
                        child: Text(
                          l10n.all,
                          style: TextStyle(
                            color: const Color(0xFFFFFFFF),
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
    );
  }

  Widget _buildBalanceInfo(AppLocalizations l10n) {
    return GetBuilder<WithdrawController>(
      builder:
          (controller) => Column(
            children: [
              Row(
                children: [
                  Text(
                    l10n.currentBalance,
                    style: TextStyle(
                      color: Color(0xFF05FFFD),
                      fontSize: 10.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  Text(
                    '${controller.currentBalance.value} btc',
                    style: TextStyle(
                      color: Color(0xFF05FFFD),
                      fontSize: 10.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 5.h),
              Row(
                children: [
                  Text(
                    l10n.withdrawalAmount,
                    style: TextStyle(
                      color: const Color(0xFF05FFFD),
                      fontSize: 10.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  Text(
                    '${controller.withdrawalAmount.value} btc',
                    style: TextStyle(
                      color: Color(0xFF05FFFD),
                      fontSize: 10.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ],
          ),
    );
  }

  Widget _buildWithdrawButton(AppLocalizations l10n) {
    return GetBuilder<WithdrawController>(
      builder:
          (controller) => GestureDetector(
            onTap: controller.executeWithdrawal,
            child: Container(
              width: 198.w,
              height: 60.w,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage("assets/images/bg_withdraw_inner.png"),
                  fit: BoxFit.fill,
                ),
              ),
              child: Center(
                child: Text(
                  l10n.withdraw,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
    );
  }

  void _showMethodSelector() {
    final controller = Get.find<WithdrawController>();

    // 显示弹窗
    controller.showMethodSelector.value = !controller.showMethodSelector.value;
  }

  Widget _buildMethodSelectorPopup(AppLocalizations l10n) {
    final controller = Get.find<WithdrawController>();

    return Obx(() {
      if (!controller.showMethodSelector.value) {
        return const SizedBox.shrink();
      }

      // 获取屏幕尺寸
      final screenHeight = MediaQuery.of(Get.context!).size.height;

      // 使用固定位置，基于提现方式选择区域的位置
      // 提现方式选择通常在页面顶部，我们计算一个合适的位置
      final double popupTop = 240.h; // 提现方式选择区域下方
      final double popupRight = 20.w; // 右侧边距

      // 确保弹窗不会超出屏幕底部
      final popupHeight = 120.h; // 预估弹窗高度
      final maxTop = screenHeight - popupHeight - 20.h;
      final finalTop = popupTop > maxTop ? maxTop : popupTop;

      return Positioned(
        top: finalTop,
        right: popupRight,
        child: Container(
          width: 1.sw - 40.w,
          decoration: BoxDecoration(
            color: const Color(0xFF0084FF).withValues(alpha: 0.9),
            borderRadius: BorderRadius.circular(10.r),
            border: Border.all(color: const Color(0xFF05FFFD), width: 1.w),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 选项列表
              Column(
                children:
                    controller.withdrawalMethods.map((method) {
                      final isSelected =
                          method == controller.selectedMethod.value;
                      return _buildMethodOption(
                        method,
                        isSelected,
                        () => controller.selectWithdrawalMethod(method),
                      );
                    }).toList(),
              ),
            ],
          ),
        ),
      );
    });
  }

  Widget _buildMethodOption(String title, bool isSelected, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          color:
              isSelected
                  ? const Color(0xFF00FFFF).withOpacity(0.2)
                  : Colors.transparent,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: isSelected ? const Color(0xFF061125) : Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
